import time
import requests
import csv
from constants import *
from app import App

class Report:
	title = ""
	start_date = None
	end_date = None
	group_by = "DAYS"
	apps = []
	app_keys = None
	header_written = False

	def __init__(self, title, startdate, enddate, groupby, appkeys = None):
		self.title = title
		self.start_date = startdate
		self.end_date = enddate
		self.group_by = groupby

		if appkeys:
			self.app_keys = appkeys

		self.get_apps()



	def get_apps(self):
		p = {'apiAccessCode' : APIACCESSCODE}

		if self.app_keys:
			if isinstance(self.app_keys, tuple):
				for app_key in self.app_keys:
					p = {'apiAccessCode' : APIACCESSCODE, 'apiKey' : app_key}
					time.sleep(1.100)
					r = requests.get('http://api.flurry.com/appInfo/getApplication', params = p)
					app = r.json()
					a = App(app['@name'], app['@platform'], app_key)
					self.apps.append(a)
			else:
				p = {'apiAccessCode' : APIACCESSCODE, 'apiKey' : self.app_keys}
				time.sleep(1.100)
				r = requests.get('http://api.flurry.com/appInfo/getApplication', params = p)
				app = r.json()
				a = App(app['@name'], app['@platform'], self.app_keys)
				self.apps.append(a)
				
		else:
			r = requests.get('http://api.flurry.com/appInfo/getAllApplications', params = p)
	
			applications = r.json()
			applications['application'].sort()

			for app in applications['application']:
				a = App(app['@name'], app['@platform'], app['@apiKey'])
				self.apps.append(a)

	def generate(self):
		#check on content as well
		print "Generate report"
		if self.apps:
			for app in self.apps:
				app.get_app_stats(self)

			self.write_stats_to_csv()


	def write_stats_to_csv(self):
		print "Write stats to csv"
		print self.apps
		statics = ('Appname', 'Platform', 'Type')
		fieldnames = []
		for fieldname in statics:
			fieldnames.append(fieldname)

		for metric, value in self.apps[0].stats.days.iteritems():
			for day, val in value.iteritems():
				fieldnames.append(day.encode('utf8'))

		with open("data/" + self.title + ".csv", "wb") as csvfile:
			statwriter = csv.DictWriter(csvfile, fieldnames)

			for app in self.apps:
				self.write_stats(app, statwriter)

	def write_stats(self, app, statwriter):
		row = dict()
		
		row.update({'Appname' : app.name, 'Platform' : app.platform, 'Type' : app.stats.metric})
		for metric, value in app.stats.days.iteritems():
			for day, val in value.iteritems():
				row.update({day.encode('utf8') : val.encode('utf8')})

		if self.header_written == False:
			statwriter.writeheader()
			self.header_written = True
		statwriter.writerow(row)

	def __str__(self):
		return "Report (%s, %s, %s, %s, %s)" % (self.title, self.start_date, self.end_date, self.group_by, self.apps)


if __name__ == "__main__":
	# Z4G89SJVYJ762BNCPJBC - TV 2 TVTID iPhone
	# HDTXS2HSHX3ZWT854BQJ - TV 2 Nyhedscenter iPhone
	# AZI8Q13C6W9V29FMEPVF - Sportscenter iPhone
	# Z12GL3MN2DZVSFPCF4KP - Play iPhone

#	app_keys = ("Z4G89SJVYJ762BNCPJBC")
	app_keys = ("Z4G89SJVYJ762BNCPJBC",
		"HDTXS2HSHX3ZWT854BQJ",
		"AZI8Q13C6W9V29FMEPVF",
		"Z12GL3MN2DZVSFPCF4KP")
#	app_keys = None

        report = Report("Test", "2013-09-23", "2013-12-11", "GroupBy", app_keys)

#	print report.apps[1].name

	report.generate()
#	report.apps[1].get_app_stats(report)
#	report.write_app_stats_to_csv(report.apps[1])

